package com.fablezj.trackgen.controller.api;

import com.fablezj.trackgen.vo.Result;
import com.fablezj.trackgen.dto.Track;
import com.fablezj.trackgen.service.TrackService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 轨迹API控制器
 *
 * @author afeey
 */
@Controller
@ResponseBody
public class TrackApiController {

    private static final Logger logger = LoggerFactory.getLogger(TrackApiController.class);

    @Autowired
    private TrackService trackService;

    @RequestMapping(value = "/api/track/save")
    public Object save(String imei, double lng, double lat) {
        Assert.notNull(imei, "imei can not null");
        Assert.hasLength(imei, "imei can not empty");
        Assert.notNull(lng, "lng can not null");
        Assert.notNull(lat, "lat can not null");

        Track track = new Track();
        track.setImei(imei);
        track.setLng(lng);
        track.setLat(lat);
        track.setGpsTime(new Date());
        trackService.save(track);

        logger.info("save a track. {},{},{}", imei, lng, lat);

        // 组装返回对象
        Result result = new Result(true,"保存成功");
        return result;
    }

    /**
     * 查询多个IMEI最新轨迹点
     *
     * @param imeis IMEI集合
     * @return json
     */
    @RequestMapping("/api/track/last_track")
    public Map<String, Object> lastTrack(String imeis) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (imeis == null) {
            map.put("ret", 0);
            map.put("msg", "imeis参数不能为null");
            return map;
        }

        // 获取imei列表
        List<String> imeiList = new ArrayList<String>();
        String[] imeiArr = imeis.split(",");
        for (String imei : imeiArr) {
            imeiList.add(imei);
        }

        // 获取最后轨迹点集合
        List<Track> tracks = trackService.queryLastTracks(imeiList);

        // 组装返回对象
        map.put("ret", 0);
        map.put("msg", "");
        map.put("data", tracks);

        logger.info("query last track.");

        return map;
    }

}
